var imgFormulaWarning = "resources/images/btnWarning.png";

function reuseComponent(srcElement, cmpType, additionalAttributes)
{
	var selectedComponent = null;
	var reqLoad = getXmlHttpRequestObject(); 
	
	function handleRequest()  
	{  
		if (reqLoad.readyState == 4 && reqLoad.status == 200) 
	    {
	     	eval("var response = ("+reqLoad.responseText+")");
	     	
	     	if(response == "ERROR")
	     		alert("error!!!!!!!!!!");
	     	else
	     	{
	     		if(additionalAttributes != null)
	     			for(var prop in additionalAttributes)
	     				response[prop] = additionalAttributes[prop];
	     		
	     		response["cmpType"] = cmpType;
	     		selectedComponent = showModalDialog("searchFilterView.jsp", response, 'unadorned:yes;resizable:1;dialogHeight:550px;dialogwidth:700px;scroll:yes;status=no;resizable:no');
	     		
	     	}
	    }
	}
	
	sendRequest(reqLoad, "reuse", "loadSearchData", handleRequest);
	return selectedComponent;
}

function reuseMethod(srcElement)
{
	var selectedComponent = reuseComponent(srcElement, "METHOD");
	if(selectedComponent != null)
		alert("Method Selected: " + selectedComponent.component.name);
}

function reuseValue(srcElement)
{
	function mappData(srcElement, value)
	{
		var oldValueID = srcElement.id.replace("link","");
		var parentCell = findParentByTagName(srcElement, "TD");
		
		var resultField = getChildElementByProperty(parentCell, "id", "result" + oldValueID);
		resultField.id = resultField.name ="result" + value.ID;
		resultField.value = value.stringResult;
		resultField.title = "Source: " + value.source;
		var unitField = getChildElementByProperty(parentCell, "id", "unit" + oldValueID);
		unitField.id = unitField.name = "unit" + value.ID;
		unitField.value = value.unit;
		var valueIdentifier = getChildElementByProperty(parentCell.parentNode, "value", oldValueID);
		valueIdentifier.value = value.ID;
		
		srcElement.id = "link" + value.ID;
		
		if(value.reuseMode == "LINK")
		{
			resultField.disabled = true;
			unitField.disabled = true;
		}
	}
	
	var selectedComponent = reuseComponent(srcElement, "VALUE");
	if(selectedComponent != null)
		mappData(srcElement, selectedComponent);
}

function reuseCase(srcElement)
{
	function replaceCase(srcElement, caso, metID)
	{
		//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
		var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
		
		try
		{
			var oldCaseID = srcElement.id.replace("link","");
			var table = findParentByTagName(srcElement, "TABLE");
			
			var oldMethodApplication = getChildElementByProperty(table, "name", "methodApplications" + table.id + oldCaseID); 
			oldMethodApplication.name = oldMethodApplication.name.replace(oldCaseID, caso.ID);
			oldMethodApplication.id = (caso.values[table.id] != null) ? caso.values[table.id].metAppID : generateID();
			
			getChildElementByProperty(table, "id", oldCaseID).id = caso.ID; 
			
			var caseInput = getChildElementByProperty(table, "id", "name" + oldCaseID);
			caseInput.id = "name" + caso.ID;
			caseInput.name = "name" + caso.ID;
			caseInput.value = caso.name;
			
			document.getElementById("link" + oldCaseID).id = "link" + caso.ID;
			
			var metParameters = getChildElementsByProperty(table, "name", "params" + metID);
			for(var j = 0 ; j < metParameters.length ; j++)
			{
				var metApplication = getChildElementByProperty(table, "name", "methodApplications" + metParameters[j].id + oldCaseID); 
				metApplication.name = "methodApplications" + metParameters[j].id + caso.ID; 
				metApplication.id = generateID();
				
				var metID = generateID();
				var value = {"ID": generateID(), "stringResult": "", "unit": ""};
				var caseValue = caso.values[metParameters[j].id];
				if(caseValue != null)
				{
					metID = caseValue.methodID;
					value = caseValue.value;
					metApplication.id = caseValue.metAppID;
				}
				
				var relatedMethod = searchElementInArrayByProperty("value", oldCaseID, getChildElementsByProperty(table, "name", "methods" + metParameters[j].id));
				var valueIdentifier = getChildElementByProperty(table, "id", "value" + relatedMethod.id + oldCaseID);  
				
				var valueResult = findElementByColumnID(getChildElementsByProperty(table, "name", "result" + valueIdentifier.value), "case" + oldCaseID);
				var valueUnit = findElementByColumnID(getChildElementsByProperty(table, "name", "unit" + valueIdentifier.value), "case" + oldCaseID);
				valueResult.id = "result" + value.ID;
				valueResult.title = value.source;
				valueResult.name = "result" + value.ID;
				valueResult.value = value.stringResult;
				valueUnit.id = "unit" + value.ID;
				valueUnit.name = "unit" + value.ID;
				valueUnit.value = value.unit;
				var valueLink = findElementByColumnID(getChildElementsByProperty(table, "id", "link" + valueIdentifier.value), "case" + oldCaseID);
				valueLink.id = "link" + value.ID;
				
				//Updating the references...
				findParentByTagName(valueResult, "TD").id = "case" + caso.ID;
				valueIdentifier.id = "value" + metID + caso.ID;
				valueIdentifier.value = value.ID;
				relatedMethod.value = caso.ID;
				relatedMethod.id = metID;
			}
			//TODO: Think about a way to take this warning symbol off later...
			var forWarning = getChildElementByProperty(table, "id", "formulaWarning" + oldCaseID);
			var resultColumn = getChildElementByProperty(table, "id", "finalResultColumn" + oldCaseID);
			if(forWarning == null)
			{
				forWarning = createImageButton("formulaWarning" + caso.ID, imgFormulaWarning, null, "smallImgButton");
				forWarning.title = "Formula is outdated. Please update the formula.";
				resultColumn.appendChild(forWarning);
			}
			
			resultColumn.id = resultColumn.id.replace(oldCaseID, caso.ID); //Updating reference...
		}
		catch(ex)
		{
			showErrorMessage("There was a problem while trying to insert a new Case to the Business Case and the action couldn't be completed.", "Javascript Error");
			document.getElementById("frMethod").innerHTML = cachedForm;
		}
	}
	
	var table = findParentByTagName(srcElement, "TABLE");
	var metID = getChildElementByProperty(table, "id", "method" + table.id).value; 
	var parentCalMetID = getChildElementByProperty(table, "id", "method" + table.id).value; 
	var selectedComponent = reuseComponent(srcElement, "CASE", {"parentMetID": parentCalMetID});
	
	if(selectedComponent != null)
		replaceCase(srcElement, selectedComponent, metID);
}

function reuseCriterion(srcElement)
{
	function replaceCriterion(srcElement, criterion)
	{
		//IE BUG: We have to use the innerHTML from the form because the IE has a bug that doesn't allow to change the table.innerHTML
		var cachedForm =  document.getElementById("frMethod").innerHTML; //Save the form state, so if a problem happen we can undo the changes
		
		try
		{
			var table = findParentByTagName(srcElement, "TABLE");
			var currentRow = findParentByTagName(srcElement, "TR");
			var oldParamID = srcElement.id.replace("link","");
			srcElement.id = srcElement.id.replace(oldParamID, criterion.ID);
			
			var nameInput = getChildElementByProperty(currentRow, "id", "name" + oldParamID); 
			nameInput.value = criterion.name;
			nameInput.id = nameInput.id.replace(oldParamID, criterion.ID);
			nameInput.name = nameInput.name.replace(oldParamID, criterion.ID);
			
			if(criterion.reuseMode == "LINK")
				nameInput.disabled = true;
			
			var criterionMethods = getChildElementsByProperty(table, "name", "methods" + oldParamID);
			var criterionCases = getChildElementsByProperty(table, "name", "caso" + table.id);
			for(var i = 0 ; i < criterionCases.length ; i++)
			{
				var caseID = criterionCases[i].id;
				var metApplication = getChildElementByProperty(currentRow, "name", "methodApplications" + oldParamID + caseID); 
				metApplication.id =  generateID();
				metApplication.name = "methodApplications" + criterion.ID + caseID;
				
				var metID = generateID();
				var value = {"ID": generateID(), "stringResult": "", "unit": ""};
				var crtValue = criterion.values[caseID];
				if(crtValue != null)
				{
					metID = crtValue.methodID;
					value = crtValue.value;
					metApplication.id = crtValue.metAppID;
				}
				
				var method = searchElementInArrayByProperty("value", caseID, criterionMethods);
				var valueIdentifier = getChildElementByProperty(currentRow, "id", "value" + method.id + caseID); 
				method.value = caseID;
				method.id = metID;
				
				var valueResult = getChildElementByProperty(currentRow, "id", "result" + valueIdentifier.value); 
				valueResult.id = "result" + value.ID;
				valueResult.name = "result" + value.ID;
				valueResult.value = value.stringResult;
				
				var valueUnit = getChildElementByProperty(currentRow, "id", "unit" + valueIdentifier.value); 
				valueUnit.id = "unit" + value.ID;
				valueUnit.name = "unit" + value.ID;
				valueUnit.value = value.unit;
				
				var valueLink = getChildElementByProperty(currentRow, "id", "link" + valueIdentifier.value); 
				valueLink.id = "link" + value.ID;
				
				valueIdentifier.id = "value" + metID + caseID;
				valueIdentifier.value = value.ID;
			}
			
			var oldParameterIdentifier = getChildElementByProperty(table, "id", oldParamID);
			oldParameterIdentifier.id = criterion.ID;
			
			for(var i = 0 ; i < criterionMethods.length ; i++)
				criterionMethods[i].name = "methods" + criterion.ID;
			
			currentRow = currentRow.id.replace(oldParamID, criterion.ID);
		}
		catch(ex)
		{
			showErrorMessage("There was a problem while trying to insert a new method to the Business Case and the action couldn't be completed.", "Javascript Error");
			document.getElementById("frMethod").innerHTML = cachedForm;
		}
	}
	
	var table = findParentByTagName(srcElement, "TABLE");
	var parentCalMetID = getChildElementByProperty(table, "id", "method" + table.id).value; 
	
	var selectedComponent = reuseComponent(srcElement, "CRITERION", {"parentMetID": parentCalMetID});
	if(selectedComponent != null)
		replaceCriterion(srcElement, selectedComponent);
}